package com.nineclock.document.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.document.dto.DocFolderDto;
import com.nineclock.document.mapper.DocFolderMapper;
import com.nineclock.document.pojo.DocFolder;
import com.nineclock.document.service.DocFolderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class DocFolderServiceImpl implements DocFolderService {

    //-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    @Autowired
    DocFolderMapper docFolderMapper;

//====================================================================================================

    /**
     * 新增文件夹 -- 新增一条数据到数据库
     * 1.文件夹重名 \ 参数判空
     * 2.插入
     *
     * @docFolderDto 接收参数
     */
    @Override
    public void insertFolder(DocFolderDto docFolderDto) {
        //参数判空
        if (docFolderDto == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //文件名重复判断
        LambdaQueryWrapper<DocFolder> queryWrapper = new LambdaQueryWrapper<DocFolder>();
        queryWrapper.eq(DocFolder::getName, docFolderDto.getName());
        queryWrapper.eq(DocFolder::getCompanyId, docFolderDto.getCompanyId());
        if (docFolderMapper.selectOne(queryWrapper) != null) {
            throw new NcException(ResponseEnum.FILE_EXISTS);
        }
        //插入数据库
        DocFolder docFolder = new DocFolder();
        Long parentId = docFolderDto.getParentId();
        if (parentId == null) {
            docFolder.setParentId(0L);
        } else {
            // 当前所在文件夹 id 为父 id
            docFolder.setParentId(parentId.longValue());
        }
        docFolder.setCompanyId(CurrentUserHolder.get().getCompanyId());
        docFolder.setCreateTime(new Date());
        docFolder.setCreateUserId(CurrentUserHolder.get().getCompanyUserId());
        docFolder.setName(docFolderDto.getName());
        docFolder.setOrderNum(0);
        docFolder.setStatus((short) 1);
        System.out.println("正在插入文件......");
        docFolderMapper.insert(docFolder);
    }
}
